package com.whirl.org.service.Impl;

import com.whirl.basic.service.impl.BaseServiceImpl;
import com.whirl.org.entity.Department;
import com.whirl.org.mapper.DepartmentMapper;
import com.whirl.org.service.DepartmentService;
import com.whirl.org.query.DepartmentQuery;
import com.whirl.basic.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author xiaowei
 * @date 2022/6/12 20:59
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void insert(Department department) {
        /**
         * 思路：传进来，如果有parent_id，就存放到数据库中
         * 1、需要拿到主键ID，因为数据库字段是自增的
         * 2、判断是否有父部门
         * 2.1 如果有父部门，就拿到父部门的dirPath，这样存的数据就是 dirPath +"/"+ id
         * 2.2 如果没有父部门，那当前的部门就是顶级部门，存的数据就是 "/"+ id
         * 3、将dirPath入库
         */
        departmentMapper.insert(department);
        // 调用更新的方法，来增加dirPath字段
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        // 因为这个添加dirPath字段，在更新和修改里都需要用到，所以写在更新里，以此来复用
        String dirPath = "";
        // 拿的到父部门的id
        if (department.getParent() != null && department.getParent().getId() != null) {
            // 拿到父部门的主键ID 以及 这个对象
            Long id = department.getParent().getId();
            Department parentDept = departmentMapper.selectById(id);
            // 父部门的dirPath拼接当前的id
            dirPath = parentDept.getDirPath() + "/" + department.getId();
        } else {
            dirPath = "/" + department.getId();
        }
        // 入库
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }


    @Override
    public List<Department> queryTree() {
        return departmentMapper.queryTree();
    }
    
}
